<template>
  <div class="container">
    <el-drawer
      custom-class="wxkj-drawer forward-drawer"
      :title="drawerTitle"
      :visible.sync="drawerShow"
      :destroy-on-close="true"
      size="500"
    >
      <div class="drawer-content">
        <el-form ref="form" :model="form" :rules="rules">
          <el-form-item label="" prop="roleName" />
          <el-tree ref="tree" :data="menuTree" node-key="id" :default-checked-keys="default_checked" :check-strictly="check_strictly" show-checkbox highlight-current :props="defaultProps" />
          <el-form-item style="margin-top: 100px">
            <el-dropdown placement="top-start" @command="handleCommand">
              <el-button type="primary">
                更多菜单<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="check_strictly_false">父子关联</el-dropdown-item>
                <el-dropdown-item command="check_strictly_true">取消关联</el-dropdown-item>
                <el-dropdown-item command="check_all">全部勾选</el-dropdown-item>
                <el-dropdown-item command="uncheck_all">取消全选</el-dropdown-item>

              </el-dropdown-menu>
            </el-dropdown>
            <div class="fr">
              <el-button @click.native="drawerShow = false">取消</el-button>
              <el-button type="primary" @click.native="submit(0)">保存</el-button>
              <el-button type="primary" @click.native="submit(1)">保存并关闭</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { sys_role_queryRolePermission, sys_role_saveRolePermission } from '@/api/sys_role'
import { menu_list } from '@/api/sys_menu'
export default {
  components: {},
  props: {},
  data() {
    return {

      drawerTitle: '',
      drawerShow: false,
      roleId: '',
      check_strictly: true, // 在显示复选框的情况下，是否严格的遵循父子不互相关联的做法，默认为 false
      menuTree: [],
      default_checked: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      form: {
        id: '',
        roleCode: '',
        roleName: ''
      },
      value: '',
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleCode: [
          { required: true, message: '请输入角色编码', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    drawerShow(bl) {
      console.log('' + bl)
      if (!bl) {
        this.$refs.form.resetFields()
        this.check_strictly = true
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 销毁
  destroyed() {},
  // 方法
  methods: {
    handleCommand(command) {
      console.log('commandcommandcommandcommandcommand', command)
      // this.$message('click on item ' + command);

      if (command == 'check_strictly_false') {
        console.log('父子关联', command)
        this.check_strictly = false
      } else if (command == 'check_strictly_true') {
        console.log('取消关联', command)

        this.check_strictly = true
      } else if (command == 'uncheck_all') {
        console.log('取消全选', command)

        this.$refs.tree.setCheckedKeys([])
      } else if (command == 'check_all') {
        this.$refs.tree.setCheckedNodes(this.menuTree)
      }
    },
    // 输入整数
    formInput(e) {
      this.form[e] = this.form[e].replace(/[^\d]/g, '')
    },
    // 弹窗打开
    show(roleId) {
      this.default_checked = []
      this.roleId = roleId
      // this.topBlockId=topBlockId;
      this.drawerTitle = '授权'
      this.drawerShow = true

      menu_list({}).then(response => {
        const list = response.result
        const menuTree = []
        // console.log("form "+this.form.parentId)
        for (let i = 0; i < list.length; i++) {
          const element = list[i]
          if (element.id == this.form.parentId) {
            // console.log("相同"+element.name);
            this.parentIdLabel = element.name
          }
          if (element.id != this.form.id) { // 排除自己
            menuTree.push(element)
          }

          // console.log(element);
        }
        this.menuTree = menuTree

        sys_role_queryRolePermission({ 'roleId': this.roleId }).then(response => {
          this.default_checked = response.result
          this.$nextTick(() => {
            this.check_strictly = false
          })
        })// end of sys_role_queryRolePermission
      })// end of menu_list
    },

    // 保存
    submit(closeFlag) {
      const p = { 'roleId': '', 'permissionIds': '', 'lastpermissionIds': this.default_checked.join(',') }// {"roleId":"","permissionIds":"8d4683aacaa997ab86b966b464360338,1176679204206522369","lastpermissionIds":""}
      p.roleId = this.roleId
      // console.log("==================>",this.$refs.tree.getCheckedNodes());
      const nodes = [...this.$refs.tree.getCheckedNodes(), ...this.$refs.tree.getHalfCheckedNodes()]
      let permissionIds = ''
      for (let i = 0; i < nodes.length; i++) {
        const element = nodes[i]
        // console.log("xxxxx",element.id,element.name);
        permissionIds += element.id
        if (i != nodes.length - 1) {
          permissionIds += ','
        }
      }
      p.permissionIds = permissionIds
      console.log('permissionIds', permissionIds)
      // return;

      sys_role_saveRolePermission(p).then(response => {
        this.$message({
          type: 'success',
          message: this.form.id ? '保存成功!' : '添加成功！'
        })

        if (closeFlag == 1) this.drawerShow = false
        // this.$emit('refresh')
      })

      // this.$refs.form.validate((valid) => {
      //   if (valid) {
      //     console.log(this.form)
      //     if(''==this.form.id){
      //
      //     }else {
      //       sys_role_edit(this.form).then(response => {
      //         this.$message({
      //           type: 'success',
      //           message: this.form.id ? '保存成功!' : '添加成功！'
      //         })
      //         this.drawerShow = false
      //         this.$emit('refresh')
      //       })
      //     }//end of if-else
      //
      //
      //
      //
      //   }
      // })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
